#include "factory.h"
//初始化线程池
int factory_init(Factory_t *pf,int thread_num,int capacity)
{
    que_init(&pf->que,capacity);
    int ret=pthread_cond_init(&pf->cond,NULL);
    THREAD_ERR_CHECK(ret,"pthread_cond_init");
    pf->pthid=(pthread_t *)calloc(thread_num,sizeof(pthread_t));//存放所有线程的id
    pf->start_flag=0;
}
//启动子线程
int factory_start(Factory_t *pf,int thread_num)
{
    if(!pf->start_flag)
    {
        for(int i=0;i<thread_num;i++)
        {
            pthread_create(pf->pthid+i,NULL,thread_handle,pf);
            printf("thread %ld is ready\n",*pf->pthid+i);
        }
        pf->start_flag=1;
    }
}

//释放锁资源
void cleanup(void *p)
{
    pthread_mutex_unlock((pthread_mutex_t*)p);
}

void* thread_handle(void *p)
{
    Factory_t *pf=(Factory_t *)p;
    pQue_t pq=&pf->que;
    //用来取队列中的结点
    pNode_t pcur=NULL;
    while(1)
    {
        pthread_mutex_lock(&pq->mutex);
        pthread_cleanup_push(cleanup,&pq->mutex);
        if(0==pq->que_size)
        {
            pthread_cond_wait(&pf->cond,&pq->mutex);
        }
        que_get(pq,&pcur);
        //通过pop解锁，以免退出的时候发生死锁
        pthread_cleanup_pop(1);
        //若pcur不为null则说明拿到了节点，任务结束后置为null
        if(pcur)
        {
            tran_file(pcur->new_fd);
            free(pcur);
            pcur=NULL;
        }
    }
}